package com.sxy.web.request;
/**
 * @author 宋鑫宇
 * @version 1.0
 * 解决请求中文乱码问题
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/req3")
public class RequestDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
            Post请求方式处理乱码问题
         */
        //1.先设置字符输入流的编码，写到获取数据之前
        request.setCharacterEncoding("UTF-8");

        //2.获取username
        String username = request.getParameter("username");
        System.out.println(username);

        /*
            Get请求方式解决中文乱码问题
                getQueryString
            乱码出现原因tomcat进行URL解码，默认的字符集是ISO_8859_1
         */
         //   先对乱码数据进行编码，转为字节数组
        /*byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
        //    对字节数组进行解码
        username = new String(bytes, "UTF-8");
        //  进行简化书写*/
        //此方法get和post请求方式通用
        username = new String(username.getBytes(StandardCharsets.ISO_8859_1),"UTF-8");
        System.out.println(username);

        //获取请求转发的数据
        Object msg = request.getAttribute("msg");
        System.out.println(msg);


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
